/*
 * @Author: 胡海
 * @Date: 2020-04-04 20:32:52
 * @LastEditors: 胡海
 * @LastEditTime: 2020-04-04 21:05:22
 * @Description: 
 */
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const TcbRouter = require('tcb-router')

const db = cloud.database()

const wxContext = cloud.getWXContext()
const shopCartCollection = db.collection('shopCart')



// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })

  app.router('addGoods', async (ctx, next) => {
    let w = {
      id: event.id
    }
    let p = await shopCartCollection.where(w).get().then((res) => {
      return res.data
    })
    if (p) {
      await shopCartCollection.where({
        cpId: p.cpId
      }).update({
        data: {
          buyNum: db.command.inc(1),
        }
      })
    } else {
      await shopCartCollection.add({
        data: {
          _openid: wxContext.OPENID,
          img: event.img,
          text: event.text,
          price: event.price,
          cpId: event.cpId,
          buyNum: 1,
        }
      })
    }
    ctx.body = {
      code: 0,
      msg: 'ok',
      data
    }
  })



  return app.serve()
}